package com.jf.identity.service.impl;

import com.jf.identity.dao.vis.ExamSessionDao;
import com.jf.identity.dao.visexamid.ExaminerDao;
import com.jf.identity.entity.*;
import com.jf.identity.exception.ServiceException;
import com.jf.identity.holder.ExamBaseParamHolder;
import com.jf.identity.service.ExaminerService;
import com.jf.identity.util.Params;
import com.jf.identity.util.PostPictureUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by x on 2018/4/11.
 */
@Service
public class ExaminerServiceImpl implements ExaminerService {
    private static final String EXAMINER = "1";
    @Resource
    private ExamBaseParamHolder examBaseParamHolder;
    @Resource
    private ExamSessionDao examSessionDao;
    @Resource
    private ExaminerDao examinerDao;
    @Resource
    private ExamBaseParamValidator examBaseParamValidator;

    @Override
    public List<LogicExamRoom> getExaminerRelInfo(ExamBaseParam examBaseParam) {
//        ExamBaseParam examBaseParam = examBaseParamHolder.getExamBaseParam();
        Params.isBlank(examBaseParam, " 考试信息");
        examBaseParamValidator.validate(examBaseParam, ExamBaseParam.ORGCODE, ExamBaseParam.EXAM_ID);
        String examId = examBaseParam.getExamId();
        Integer sessionMax = examSessionDao.getExamSessionSum(examId);
        Integer sessionMin = examSessionDao.getExamSessionMin(examId);
        if (sessionMax == null || sessionMin == null) {
            return new ArrayList<>();
        }
        List<LogicExamRoom> list = new ArrayList<>();
        for (int i = sessionMin; i <= sessionMax; i++) {
            examBaseParam.setExamSessionNum(Integer.toString(i));
            List<LogicExamRoom> newList = examinerDao.getExaminerRelInfo(examBaseParam);
            if (newList != null && !newList.isEmpty()) {
                for (LogicExamRoom l : newList) {
                    if (!StringUtils.isEmpty(l)) {
                        for (Examiner e : l.getExaminers()) {
                            String url = e.getPhoto();
                            if (!StringUtils.isEmpty(url)) {
                                File file = new File(PostPictureUtil.drive + url);
                                if (file.exists()) {
                                    Path path = file.toPath();
                                    String str;
                                    try {
                                        byte[] bytes = Files.readAllBytes(path);
                                        str = Base64Utils.encodeToString(bytes);
                                        e.setPhoto(str);
                                    } catch (IOException ex) {
                                        throw new ServiceException("文件错误", ex);
                                    }
                                }
                            }
                        }
                    }
                }
                list.addAll(newList);
            }
        }
        return list;
    }

    @Override
    public boolean insertExaminerVerifyInfo(ExaminerVerifyInfo examiners) {
        ExamBaseParam examBaseParam = ExamBaseParam.copyOf(examiners);
        Params.isBlank(examBaseParam, " 考试信息");
        examBaseParamValidator.validate(examBaseParam, ExamBaseParam.EXAM_ID, ExamBaseParam.EXAM_SESSION_NUM,
                ExamBaseParam.ORGCODE, ExamBaseParam.LOGIC_EXAM_ROOM_NUM, ExamBaseParam.DEVICE_ID);
        //todo:对传入的信息进行入库，如果监考员上传信息包含头像，则按以下步骤处理头像入库问题
        /*
         * ① 将头像存入本地，并获得待入库的存储路径
         * ② 取出数据库中保存的图片路径
         * ③ 将待入库的图片路径，写入数据库中
         * ④ 如果写入数据库成功则将第二步取出的图片路径(前提是存在)进行删除文件操作
         */
        int n = 0;
        for (Examiner examiner : examiners.getExaminers()) {
            String picOldPath = null;
            String uid = getExamierSignUid(examBaseParam, examiner);
            if (!StringUtils.isEmpty(examiner.getImage())) {
                String picPath = PostPictureUtil.postPicAtLocal(examiner.getImage(), "2", examBaseParam.getExamId());
                picOldPath = examinerDao.getExaminerImageUrl(examBaseParam, examiner);
                examiner.setUid(uid);
                examiner.setImage(picPath);
            } else {
                examiner.setUid(uid);
                examiner.setImage("");
            }
            n += examinerDao.insertExaminerVerifyInfo(examBaseParam, examiner);
            if (n > 0 && !StringUtils.isEmpty(picOldPath)) {
                PostPictureUtil.deleteLocalPic(PostPictureUtil.drive + picOldPath);
            }
        }
        return n != 0;
    }

    /**
     * i_jkjsyzxx uid = MD5(orgCode+examId+examSessionNum+idCardNum+logicExamRoom)
     * 同一个教师，可能监考不同的教室。
     *
     * @param examBaseParam orgCode+examId+examSessionNum
     * @param examiner      idCardNum+logicExamRoom
     * @return uid
     */
    private String getExamierSignUid(ExamBaseParam examBaseParam, Examiner examiner) {
        String md5 = examBaseParam.getOrgCode() + examBaseParam.getExamId() + examBaseParam.getExamSessionNum()
                + examiner.getIdCardNum() + examBaseParam.getLogicExamRoomNum();
        return DigestUtils.md5DigestAsHex(md5.getBytes(Charset.forName("UTF-8")));
    }
}
